package juc.imooccache;

import juc.imooccache.computable.Computable;
import juc.imooccache.computable.MayFail;

import java.util.concurrent.*;

/**
 * @author fangbin
 * @desc   设置缓存过期日期
 * @date 2020/7/1 21:33
 */
public class ImoocCache10<A,V> implements Computable<A,V>{

    private final ConcurrentHashMap<A, Future<V>> cache = new ConcurrentHashMap();
    private Computable<A,V> c;

    public ImoocCache10(Computable<A, V> c) {
        this.c = c;
    }

    @Override
    public   V compute(A arg) throws ExecutionException, InterruptedException {
        while (true) {
            Future<V> future = cache.get(arg);
            if (future == null) {
                Thread.sleep(500);
                Callable callable = new Callable() {
                    @Override
                    public V call() throws Exception {
                        return c.compute(arg);
                    }
                };

                FutureTask ft = new FutureTask(callable);
                future = cache.putIfAbsent(arg, ft);
                if (future == null) {
                    future = ft;
                    System.out.println("从FutureTask调用了计算函数");
                    ft.run();
                }

            }


            try {
                return future.get();
            } catch (InterruptedException e) {
                //e.printStackTrace();
                throw e;
                // V v = null;
                //return v;
            } catch (ExecutionException e) {
                System.out.println("计算错误，重试线程"+Thread.currentThread().getName());
                cache.remove(arg);
                // e.printStackTrace();
               // throw e;
            } catch (CancellationException e) {
                throw e;
            }
        }

    }

    public V compute(A arg,long expire) throws ExecutionException, InterruptedException {
        ScheduledExecutorService  scheduledExecutorService = Executors.newScheduledThreadPool(5);
        if(expire>0) {
            scheduledExecutorService.schedule(new Runnable() {
                @Override
                public void run() {
                    expire(arg);
                }
            }, expire, TimeUnit.SECONDS);
        }
        return compute(arg);
    }

    public void expire(A arg){
        Future<V> future = cache.get(arg);
        if(future!=null){
            if(!future.isDone()){
                System.out.println("future任务被取消");
                future.cancel(true);
            }
            System.out.println("过期时间到，清除缓存");
            cache.remove(arg);
        }

    }
    public static void main(String[] args) throws Exception {
        ImoocCache10<String, Integer> stringIntegerImoocCache2 = new ImoocCache10<>(new MayFail());
        new Thread(new Runnable() {
            @Override
            public void run() {
                Integer result = null;
                try {
                    result = stringIntegerImoocCache2.compute("666",5);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("第一次计算结果:"+result);
            }
        }).start();

        Thread.sleep(6000);

        new Thread(new Runnable() {
            @Override
            public void run() {
                Integer result = null;
                try {
                    result = stringIntegerImoocCache2.compute("666");     //他不能立即获取到
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("第二次计算结果:"+result);
            }
        }).start();

    }
}
